package baseCom.dao.impl;

import baseCom.dao.EmpDao;
import baseCom.pojo.Emp;
import baseCom.utils.DatabaseConnection;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Component
public class EmpDaoA implements EmpDao {

    public List<Emp> getAllEmp() {
        List<Emp> empList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1. 建立数据库连接
            connection = DatabaseConnection.getConnection();

            // 2. 准备SQL查询语句
            String sql = "SELECT * FROM tb_emp";
            preparedStatement = connection.prepareStatement(sql);

            // 3. 执行查询
            resultSet = preparedStatement.executeQuery();
            System.out.println("执行查询成功");
            // 4. 处理查询结果
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String job = resultSet.getString("job");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                Timestamp entryDate = resultSet.getTimestamp("entrydate");
                String gender = resultSet.getString("gender");

                Emp emp = new Emp();
                emp.setId(id);
                emp.setName(name);
                emp.setJob(job);
                emp.setUsername(username);
                emp.setPassword(password);
                emp.setEntryDate(entryDate);
                emp.setGender(gender);

                empList.add(emp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭资源
            closeResources(connection, preparedStatement, resultSet);
        }
        return empList;
    }

    // 辅助方法：关闭资源
    private void closeResources(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

